<?php

require ('./config/init.php');

/* Instantiating new Route Object */
$route = new Route();

/* * * * * * * * * *
 *   CLIENT PART   *
 * * * * * * * * * */

/*
  Start Page
 */
$route->add('/', function() {

    include_once ('./app/models/getProducts.php');

    Load::view('./app/views/_header');
    Load::view('./app/views/main', $data);
    Load::view('./app/views/_footer');
});

/*
  Result Page
 */
$route->add('/result', function() {

    if (Input::exists('post')) {
        // getting all input from the form
        $results = Input::getAllPost();

        foreach ($results as $key => $value) {
            // making the INCLUDED selection array()
            if (substr($key, 0, 7) == 'include') {
                $include[] = (int) substr($key, 8);
            }
            // making the EXCLUDED selection array()
            if (substr($key, 0, 7) == 'exclude') {
                $exclude[] = (int) substr($key, 8);
            }
        }

        // get required data from db for filtering
        include_once ('./app/models/getAll.php');

        if (isset($exclude) && count($exclude) > 1 && isset($include) && count($include) > 1) {

            // removing all excluded products and the corresponding recipes
            foreach ($result as $key => $value) {
                foreach ($exclude as $exclude_id) {
                    // if we have a excluded product we unset its recipe id
                    // then we get the recipe id and unset all of its occurrences in the db
                    if ($value->products_id == $exclude_id) {

                        unset($result[$key]);
                        $recipeToDelete = $value->recipes_id;

                        foreach ($result as $subKey => $subValue) {
                            if ($subValue->recipes_id == $recipeToDelete) {
                                unset($result[$subKey]);
                            }
                        }
                    }
                }
            }

            // here we have again the result array but with excluded content
            foreach ($result as $recipes) {
                $recipesIDs[] = $recipes->recipes_id;
            }

            // checking if there is any result based on the uses decisions
            if (isset($recipesIDs) && count($recipesIDs) > 0) {
                $recipesIDs = array_unique($recipesIDs);
                $recipesIdString = implode(", ", $recipesIDs);

                // based on the IDs in the $recipesIdString variable
                // we get from db all the recipes with those IDs!
                // and we put it in the $data array and push it to the view.
                include_once ('./app/models/getUserRequest.php');
            }
            else {
                $data['resultError'] = 'Няма резултати за вашите изисквания до този момент! ';
                $data['resultError'] .= 'Опитайте да изберете повече продукти които харесвате.';
            }
        }
        else {
            $data['resultError'] = 'Трябва да изберете поне по два продукта от всяка секция!';
        }

        Load::view('./app/views/_header');
        Load::view('./app/views/result', $data);
        Load::view('./app/views/_footer');
    }
    else {
        Redirect::to(Config::get('URI'));
    }
});

/* * * * * * * * * *
 *   ADMIN PART    *
 * * * * * * * * * */

/*
  Admin Login Page
 */
$route->add('/admin', function() {
    if (!isset($_SESSION['isLogged'])) {

        if (Input::exists('post')) {

            $user = new Users();

            // admin access to admin-panel
            if ($user->login(Input::get('username'), Input::get('password'))) {
                $_SESSION['isLogged'] = TRUE;
                Redirect::to(Config::get('URI'));
            }
            else {
                $_SESSION['logInError'] = TRUE;
            }
        }

        // login-panel
        Load::view('./app/views/_header');
        Load::view('./app/views/admin');
        Load::view('./app/views/_footer');
    }
    else {
        Redirect::to(Config::get('URI'));
    }
});

/*
  Logout
 */
$route->add('/logout', function() {
    session_destroy();
    Redirect::to('/apocy_web/');
});

/*
  Add Recipes
 */
$route->add('/add-recipe', function() {

    if (isset($_SESSION['isLogged']) && $_SESSION['isLogged'] == TRUE) {

        if (Input::exists('post')) {

            // inserting in to recipes
            // preventing script tag inserion with str_ireplace()
            $db = DB::getInstance();
            $db->insert(Config::get('db_tables/recipes'), array(
                'title' => str_ireplace("<script>", "&lt;script&gt;", trim(Input::get('title'))),
                'recipe' => str_ireplace("<script>", "&lt;script&gt;", Input::get('recipe')),
            ));

            // getting the inserted recipe id
            $lastInsertId = $db->getLastInsertId();

            // getting all selected IDs
            $selectedIDs = Input::getAllPost();
            unset($selectedIDs['title']);
            unset($selectedIDs['recipe']);

            // inserting into database
            $sql = "INSERT INTO " . Config::get('db_tables/idJoinTable') . "(recipes_id, products_id) VALUES";

            $numberOfSelectedIDs = count($selectedIDs);
            $counter = 1;

            foreach ($selectedIDs as $selectedID => $status) {
                if ($numberOfSelectedIDs != $counter) {
                    $sql .= '(' . $lastInsertId . ', ' . $selectedID . '), ';
                }
                else {
                    $sql .= '(' . $lastInsertId . ', ' . $selectedID . ');';
                }
                $counter++;
            }

            $db->query($sql);

            // if insert successful redirect with success message
            if (!$db->error()) {
                $_SESSION['addSuccess'] = TRUE;
                Redirect::to(Config::get('URI') . 'add-recipe/');
            }
        }

        include_once ('./app/models/getProducts.php');

        Load::view('./app/views/_header');
        Load::view('./app/views/add-recipe', $data);
        Load::view('./app/views/_footer');
    }
    else {
        Redirect::to(Config::get('URI'));
    }
});

/*
  Add Products
 */
$route->add('/add-product', function() {

    if (isset($_SESSION['isLogged']) && $_SESSION['isLogged'] == TRUE) {

        // inserting product to database
        if (Input::exists('post')) {
            $db = DB::getInstance();
            $db->insert(Config::get('db_tables/products'), array(
                'name' => str_ireplace("<script>", "&lt;script&gt;", trim(Input::get('product'))),
            ));

            // if insert successful redirect with success message
            if (!$db->error()) {
                $_SESSION['addProductSuccess'] = TRUE;
                Redirect::to(Config::get('URI') . 'add-recipe/');
            }
        }
    }
    else {
        Redirect::to(Config::get('URI'));
    }
});

/*
  Recipes Listing
 */
$route->add('/recipes', function() {

    if (isset($_SESSION['isLogged']) && $_SESSION['isLogged'] == TRUE) {
        include_once ('./app/models/getRecipes.php');

        Load::view('./app/views/_header');
        Load::view('./app/views/recipes', $data);
        Load::view('./app/views/_footer');
    }
    else {
        Redirect::to(Config::get('URI'));
    }
});

/*
  Delete Recipes
 */
$route->add('/delete', function($id = array()) {

    if (isset($_SESSION['isLogged']) && $_SESSION['isLogged'] == TRUE) {
        $recipeToRemove = $id['val_1'];

        include_once ('./app/models/deleteRecipe.php');
        Redirect::to(Config::get('URI') . 'recipes/');
    }
});



/* Start Routing */
$route->submit();
